<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class district_model extends WST_Model {
	private $_table = "district";

	function __contruct(){
        parent::__construct();
    }

	public function getSingle($id=null){
		$sql = "SELECT * FROM ".$this->_table." WHERE id={$id} ";
		$query = $this->db->query($sql);
		return $query->row_array();
	}
	public function get_district($provinder_id,$flag=false){
        $all_district=  $this->cache->get('all_district_'.$provinder_id);
        if($all_district===false|| $flag===true){
            $this->db->where('provinderId',$provinder_id);
            $query = $this->db->get($this->_table);
            $this->db->order_by('orderNo','ASC');
            $all_district= $query->result_array();
            $query->free_result();
            $this->cache->save('all_district_'.$provinder_id,$all_district);
        }
		return $all_district;
	}
    public function count_all($param=array()){
        return $this->db->count_all($this->_table);
    }

    function find_all($param=array(),$current_page = 1, $page_size = 30){

        $where =" WHERE 1=1";
        if(count($param)>0){
            if(!empty($param['keyword'])){
                $where.=" AND name LIKE '%".$param['keyword']."%'";
            }
            if(!empty($param['parent'])){
                $where.=" AND parent = ".$param['parent']."";
            }
            if(!empty($param['child'])){
                $where.=" AND  parent = ".$param['child']." AND level= ".$param['parent']." ";
            }
        }
        $sql = "select * from ".$this->_table. $where."   order by id ASC";

        if ($current_page > 0 && $page_size > 0) {
            $offset = ($current_page-1)* $page_size;
            $sql .= " limit {$offset}, {$page_size}";
        }else {
            $sql .= " limit {$page_size}";
        }

        $query = $this->db->query($sql);
        $data = $query->result_array();
        $query->free_result();
        return $data;
    }

	public function insert($data=array()){

		if($this->db->insert($this->_table,$data)){
			return $this->db->insert_id();
		}
		else {
			return FALSE;
		}
	}

	public function update($data,$id=null){
		$this->db->where("id",$id);
		if($this->db->update($this->_table,$data))
			return TRUE;
		else
			return FALSE;
	}

	function getByDistrict($provinder_id){
		$sql = "SELECT * FROM ".$this->_table." WHERE provinderId= '{$provinder_id}'  ORDER BY orderNo DESC ";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
}
